<template>
    <div class="loginBox">
        <el-form :model="loginForm" :rules="rules" ref="ruleFormRef" label-width="80px">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="loginForm.password" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="login(ruleFormRef)">登录</el-button>
                <el-button type="primary" @click="reset(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
// 引入接口地址
import { userLogin } from "../request/api"
import { reactive, ref } from "vue";
//引入路由的方法
import { useRouter } from "vue-router";
//引入了数据类型规则
import { ElMessage, FormInstance, FormRules } from "element-plus";
import store from "@/store";
//引入路由的控制器
const router = useRouter();
//创建一个ref
const ruleFormRef = ref<FormInstance>();
//定义表单初始数据
const loginForm = reactive({
    username: "",
    password: "",
});
// 表单校验
let rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
    ],
})
// 点击登录
const login = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            //调用登录接口
            userLogin(loginForm).then((res: any) => {
                if (res.data.code == 200) {
                    // 派遣行动
                    store.dispatch("setUserInfo_Action", res.data.list)
                    //跳转
                    router.push('/index')
                    ElMessage({
                        type: 'success',
                        message: res.data.msg
                    })
                } else {
                    ElMessage({
                        type: 'success',
                        message: "请输入正确的内容"
                    })
                }
            })
        } else {
            console.log("验证失败", fields);
        }
    });
};
// 点击重置
const reset = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>

<style scoped lang="less">
.loginBox {
    width: 100%;
    height: 590px;
    background-color: darkorange;
    padding-top: 150px;

    .el-form {
        margin: auto;
        width: 30%;
        padding: 30px;
        background-color: #fff;
        border-radius: 20px;
    }
}
</style>
